package cn.cena.order.service.impl;

import cn.cena.basic.Exception.MyException;
import cn.cena.basic.service.impl.BaseServiceImpl;
import cn.cena.basic.util.LoginContextUtil;
import cn.cena.order.domain.OrderAddress;
import cn.cena.order.domain.OrderPet;
import cn.cena.order.domain.OrderPetDetail;
import cn.cena.order.dto.OrderDto;
import cn.cena.order.mapper.OrderAddressMapper;
import cn.cena.order.mapper.OrderPetDetailMapper;
import cn.cena.order.mapper.OrderPetMapper;
import cn.cena.order.service.IOrderPetService;
import cn.cena.pay.domain.PayBill;
import cn.cena.pay.mapper.PayBillMapper;
import cn.cena.pay.service.IPayBillService;
import cn.cena.pet.domain.Pet;
import cn.cena.pet.mapper.PetMapper;
import cn.cena.pet.service.IPetService;
import cn.cena.quartz.job.OrderOuttimeJob;
import cn.cena.quartz.util.QuartzUtil;
import cn.cena.user.domain.Logininfo;
import cn.cena.user.domain.UserAddress;
import cn.cena.user.mapper.UserAddressMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Scheduler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class OrderPetServiceImpl extends BaseServiceImpl<OrderPet> implements IOrderPetService {

    @Autowired
    private IPetService petService;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderPetMapper orderPetMapper;

    @Autowired
    private OrderPetDetailMapper orderPetDetailMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private Scheduler scheduler;

    @Transactional
    public String createOrder(OrderDto dto) {
        // 判断参数是否为空
        Long petId = dto.getPetId();
        if (petId == null){
            throw new MyException("非法请求");
        }

        Integer payWay = dto.getPayWay();
        if (payWay == null){
            throw new MyException("请选择支付方式");
        }

        Long addressId = dto.getAddressId();
        if (addressId == null){
            throw new MyException("请选择收货地址");
        }
        // 获取登录用户
        Logininfo logininfo = LoginContextUtil.getLoginContext();
        // 查询宠物，判断是否上架
        Pet pet = petService.loadOnsaleById(petId, Pet.STATE_ONSALE);
        if (pet == null){
            throw new MyException("无效商品");
        }
        // 上锁，库存减一
        synchronized (this){
            pet = petService.loadOnsaleById(petId, Pet.STATE_ONSALE);
            if(pet.getStoreNum() == null || pet.getStoreNum().intValue() == 0){
                throw new MyException("没货了");
            }

            pet.setStoreNum(pet.getStoreNum() - 1);
            pet.setShop_id(pet.getShop().getId());
            pet.setType_id(pet.getType().getId());
            pet.setUser_id(logininfo.getId());
            petService.update(pet);
        }
        // 获取用户地址
        UserAddress userAddress = userAddressMapper.findOne(addressId);

        // 生成订单，订单详情，订单地址
        OrderPet orderPet = new OrderPet();
        orderPet.setDigest("下单" + pet.getName());
        orderPet.setState(OrderPet.STATE_ORDER_ONPAY);

        // new BigDecimal("10") String类型精度更高
        orderPet.setTotalPrice(pet.getSaleprice().add(new BigDecimal("10")));

        String s = UUID.randomUUID().toString().replaceAll("-", "");
        orderPet.setOrderSn(s);
        orderPet.setPayWay(payWay);

        Date now = new Date();
        orderPet.setCreatetime(now);
        orderPet.setLastUpdateTime(now);
        //  DateUtils.addMinutes(now, 30) // lang3 工具
        Date payExpireTime = DateUtils.addMinutes(now, 30);
        orderPet.setPayExpireTime(payExpireTime);


        orderPet.setUserId(logininfo.getId());
        // 存入t_order_pet
//        super.add(orderPet);
        orderPetMapper.save(orderPet);

        // 保存t_order_pet_detail表
        OrderPetDetail orderPetDetail = new OrderPetDetail();
        orderPetDetail.setName(pet.getName());
        orderPetDetail.setResources(pet.getResources());
        orderPetDetail.setSaleprice(pet.getSaleprice());
        orderPetDetail.setState(pet.getState());
        orderPetDetail.setCreatetime(now);
        orderPetDetail.setOrderId(orderPet.getId());
        orderPetDetail.setShopId(pet.getShop().getId());
        orderPetDetail.setPetId(pet.getId());
        orderPetDetail.setOrderSn(orderPet.getOrderSn());
        orderPetDetailMapper.save(orderPetDetail);

        // 保存t_order_address
        OrderAddress orderAddress = new OrderAddress();
        // 按属性拷贝
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setCreateTime(now);
        orderAddress.setOrderId(orderPet.getId());
        orderAddress.setOrderSn(orderPet.getOrderSn());

        orderAddressMapper.save(orderAddress);

        // 创建支付单t_pay_bill
        payBillService.save(orderPet.getDigest(), orderPet.getTotalPrice(),
                orderPet.getOrderSn(), PayBill.BUSINESS_TYPE_PET,
                orderPet.getPayWay(), orderPet.getId(),
                pet.getShop().getName(), pet.getShop().getId());


        // 添加超时任务
        Map<String,String> dataMap = new HashMap<>();
        dataMap.put("orderSn",s );
        String jobName = "orderExpireJob:"+s;
        dataMap.put("jobName",jobName );

        QuartzUtil.addJob(
                scheduler, jobName, OrderOuttimeJob.class, dataMap, payExpireTime);



        return orderPet.getOrderSn();


    }
}
